package com.xbts.screen.monitor.domain.request;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbts.screen.monitor.domain.constant.MonitorConstant;
import com.xbts.screen.monitor.domain.response.RealTimeResponse;
import com.xbts.screen.monitor.domain.token.OauthConfigBaseInfo;
import com.xbts.screen.monitor.domain.util.HttpURLConnectionUtil;
import com.xbts.screen.monitor.domain.util.HttpsURLConnectionUtil;
import lombok.Data;

/**
 * 获取实时流地址
 * **/
@Data
public class RealTimeRequest extends BaseRequest<RealTimeResponse> {
    //视频通道编码
    private String channelId;
    //码流类型：1=主码流, 2=辅码流，3=辅码流2
    private String streamType;
    //hls,flv,rtmp,rtsp
    private String type;
    //数据类型
    private String dataType = "1";

    public RealTimeRequest(){}

    public RealTimeRequest(OauthConfigBaseInfo oauthConfigBaseInfo){
        super(oauthConfigBaseInfo, MonitorConstant.HTTP_POST, oauthConfigBaseInfo.getHttpConfigInfo().getPrefixUrl(), true);
    }

    @Override
    public RealTimeResponse doAction() {
        //设置请求体
        setBody();
        //获取RTSP实时流
        if(PlayBackFormatEnum.RTSP.getCode().equals(this.type)){
            this.setUrl(this.getUrl() + MonitorConstant.RTSP_REQUEST_URL);
        }
        //获取HLS/FLV/RTMP实时流
        else{
            this.setUrl(this.getUrl() + MonitorConstant.HLS_FLV_RTMP_URL);
        }

        //发送请求
        String res = isEnableHttpTest() ? HttpURLConnectionUtil.doPost(this.getUrl(), this.getBody(), this.getHeader()) : HttpsURLConnectionUtil.doPost(this.getUrl(), this.getBody(), this.getHeader());
        //获取响应
        RealTimeResponse realTimeResponse = JSON.parseObject(res, RealTimeResponse.class);

        return realTimeResponse;
    }

    public void setBody(){
        //设置请求参数
        JSONObject data = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        data.put("data", jsonObject);
        jsonObject.put("channelId",channelId);
        jsonObject.put("streamType", streamType);
        jsonObject.put("type", type);
        jsonObject.put("dataType", dataType);
        this.setBody(JSON.toJSONString(data));
    }

    public boolean isEnableHttpTest(){
        return super.getOauthConfigBaseInfo().getHttpConfigInfo().isEnableHttpTest();
    }

    public void setParam(RealTimeRequest realTimeRequest){
        this.channelId = realTimeRequest.getChannelId();
        this.streamType = realTimeRequest.getStreamType();
        this.type = realTimeRequest.getType();
    }

}
